// DBConnectionManager.cpp: implementation of the DBConnectionManager class.
//
//////////////////////////////////////////////////////////////////////

#include "StdAfx.h"
#include "AssocCommon.h"
#include "DBConnectionManager.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

namespace DAWrapper
{

DBConnectionManager* DBConnectionManager::g_Instance = 0;

DBConnectionManager::DBConnectionManager()
{
}

DBConnectionManager::~DBConnectionManager()
{
	for ( int i = 0; i < m_Connections.GetSize(); i++ )
		delete m_Connections.GetAt( i );
}

_ConnectionPtr* DBConnectionManager::GetConnectionPtrByUri( const CString& uri )
{
	for ( int i = 0; i < m_Connections.GetSize(); i++ )
	{
		if ( m_Connections.GetAt( i )->Uri() == uri )
			return m_Connections.GetAt( i )->ConnectionPtr();
	}
	return AddConnectionPtrByUriFlush( uri );
}

_ConnectionPtr* DBConnectionManager::AddConnectionPtrByUriFlush( const CString& uri )
{
//	const CString connString351 = _T( "Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data Source=" );
	const CString connString40 = _T( "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" );

	Uri2Connection* ptr = new Uri2Connection( uri );
	try
	{
		(*(ptr->ConnectionPtr()))->Open( _bstr_t( connString40 + uri ), "", "", -1 );
		m_Connections.Add( ptr );
		return ptr->ConnectionPtr();
	}
	catch( _com_error e )
	{
		ErrorAlert( e );
		ASSERT(FALSE);
		delete ptr;
		return 0;
	}
}

DBConnectionManager* DBConnectionManager::Instance() 
{
	return g_Instance ? g_Instance : ( g_Instance = new DBConnectionManager ); 
}

void DBConnectionManager::DeleteInstance() 
{ 
	if ( g_Instance )
		delete g_Instance, g_Instance = 0; 
}

}